import { check } from "@tauri-apps/plugin-updater";
import { ElMessage, ElMessageBox } from "element-plus";
import { relaunch } from "@tauri-apps/plugin-process";
export default () => {
  const checkV = async () => {
    return await check()
      .then((e: any) => {
        if (!e?.available) {
          return;
        }
        return {
          version: e.version,
          meg: `新版本 ${e.version} ,发布时间： ${e.date} 升级信息： ${e.body}`,
        };
      })
      .catch((e) => {
        console.error("检查更新错误，请稍后再试 " + e);
      });
  };

  const updater = async () => {
    ElMessageBox.confirm("您确认要更新吗 ?", "系统提示", {
      confirmButtonText: "更新",
      cancelButtonText: "不更新",
      type: "success",
    })
      .then(async () => {
        ElMessage({
          type: "success",
          message: "正在下载更新，请稍等",
        });

        await check()
          .then(async (e: any) => {
            if (!e?.available) {
              return;
            }
            await e.downloadAndInstall((event: any) => {
              switch (event.event) {
                case "Started":
                  ElMessage({
                    type: "success",
                    message:
                      "文件大小：" + event.data.contentLength
                        ? event.data.contentLength
                        : 0,
                  });
                  break;
                case "Progress":
                  ElMessage({
                    type: "success",
                    message: "正在下载" + event.data.chunkLength,
                  });
                  break;
                case "Finished":
                  ElMessage({
                    type: "success",
                    message: "安装包下载成功，10s后重启并安装",
                  });
                  setTimeout(async () => {
                    await relaunch();
                  }, 10000);
                  break;
              }
            });
          })
          .catch((e) => {
            console.error("检查更新错误，请稍后再试 " + e);
          });
      })
      .catch(() => {
        ElMessage({
          type: "info",
          message: "您已取消更新",
        });
      });
  };

  return {
    checkV,
    updater,
  };
};
